package com.haocang.szgm.activity.comm;

/**
 * 创建时间：2019/3/4
 * 编 写 人：ShenC
 * 功能描述：公用的activity
 */

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.esri.android.map.GraphicsLayer;
import com.esri.android.map.MapView;
import com.esri.android.runtime.ArcGISRuntime;
import com.esri.core.geometry.Point;
import com.esri.core.map.Graphic;
import com.esri.core.symbol.PictureMarkerSymbol;
import com.haocang.commonlib.gismap.CacheTiledServiceLayer;
import com.haocang.commonlib.gismap.GisMapConfig;
import com.haocang.commonlib.otherutil.ImageUtils;
import com.haocang.szgm.R;
import com.haocang.szgm.activity.adapter.ImageFileAdapter;
import com.haocang.szgm.activity.bean.FileIndexBean;
import com.haocang.szgm.utils.config.Config;
import com.haocang.commonlib.recyclerView.BaseAdapter;
import com.haocang.szgm.utils.tools.CacheData;
import com.haocang.szgm.utils.tools.CustomDialog;
import com.haocang.szgm.utils.tools.GetCommonParameters;
import com.haocang.szgm.utils.tools.MyTextUtils;
import com.qiniu.pili.droid.shortvideo.PLShortVideoTranscoder;
import com.qiniu.pili.droid.shortvideo.PLVideoSaveListener;

import net.tsz.afinal.FinalActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.qiniu.pili.droid.shortvideo.PLErrorCode.ERROR_LOW_MEMORY;
import static com.qiniu.pili.droid.shortvideo.PLErrorCode.ERROR_NO_VIDEO_TRACK;
import static com.qiniu.pili.droid.shortvideo.PLErrorCode.ERROR_SRC_DST_SAME_FILE_PATH;

public abstract class CommMapFinalActivity extends FinalActivity {


    protected static Context mContext;
    protected MapView mMapView;//地图控件
    protected TextView tv_map_in;//图层缩放按钮
    protected TextView tv_map_out;
    protected CacheTiledServiceLayer tileLayer;//缓存地图
    protected GraphicsLayer gLayerPos;//自定义图层
    protected GraphicsLayer gMyLocationLayer;//自定义图层
    protected CacheTiledServiceLayer pipe_tileLayer;
    protected LinearLayout tv_map_mylocation;//定位到当前位置
    protected double SingleTap_X = 0, SingleTap_Y = 0;//长按获取坐标GIS
    protected double SingleTap_MX = 0, SingleTap_MY = 0;//长按获取坐标WGS84

    protected LinearLayout bar_lin;
    protected LinearLayout iv_back;
    protected TextView tv_name;
    protected LinearLayout iv_more;
    protected ImageView iv_more_icon;


    protected boolean IsLable = true;//是否显示文字标签背景


    //附件
    protected RecyclerView mRecyclerView;
    protected ImageFileAdapter imageFileAdapter;
    protected LinearLayout media;
    protected String capturePath = null;
    protected final int REQUEST_CODE_PICK_IMAGE = 1111;//相册
    protected final int REQUEST_CODE_CAPTURE_CAMEIA = 2222;//拍照
    protected final int REQUEST_CODE_CAPTURE_VIDEO = 3333;//录像
    protected ImageView add_video1;
    protected ImageView iv_video_close;
    protected List<FileIndexBean> filelist = new ArrayList<>();
    protected List<File> vediofilelist = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ArcGISRuntime.setClientId(Config.Map_ClientId);
        mContext = this;
        initWindows();
        super.onCreate(savedInstanceState);
        setContentView(getLayoutResourceId());

        initView();

        initMap();

        initEvent();

        initMyLocation();

    }

    /**
     * 获取布局文件
     *
     * @return
     */
    protected abstract int getLayoutResourceId();

    /**
     * 是否显示bar
     *
     * @return
     */
    protected abstract boolean showNavigation();


    /**
     * 是否显示管线
     *
     * @return
     */
    protected abstract boolean showMapPipe();


    /**
     * 设置显示的图标,0为隐藏
     *
     * @return
     */

    /**
     * 多媒体
     *
     * @return
     */
    protected abstract boolean showMedia();

    protected abstract int showMoreIcon();

    /**
     * 设置标题
     *
     * @return
     */
    protected abstract String showTitleName();


    private void initMap() {
        gLayerPos = new GraphicsLayer();
        gMyLocationLayer = new GraphicsLayer();
        mMapView.setMaxScale(500);
        mMapView.setMinScale(500000);
        mMapView.setMapBackground(Color.rgb(250, 251, 246), Color.WHITE, 0, 0);//设置背景颜色
        tileLayer = new CacheTiledServiceLayer(Config.MAPBASEURL, "map");
        mMapView.addLayer(tileLayer);

        if (showMapPipe()) {
            pipe_tileLayer = new CacheTiledServiceLayer(Config.MAPPIPEURL, "pipe");
            mMapView.addLayer(pipe_tileLayer);
        }

        mMapView.addLayer(gLayerPos);
        mMapView.addLayer(gMyLocationLayer);

        mMapView.setResolution(GisMapConfig.resolution[4]);// 设置当前显示的分辨率
    }

    private void initView() {
        bar_lin = findViewById(R.id.bar_lin);
        iv_back = findViewById(R.id.iv_back);
        tv_name = findViewById(R.id.tv_name);
        iv_more = findViewById(R.id.iv_more);
        iv_more_icon = findViewById(R.id.iv_more_icon);
        tv_map_mylocation = findViewById(R.id.tv_map_mylocation);
        mMapView = findViewById(R.id.map);
        tv_map_in = findViewById(R.id.tv_map_in);
        tv_map_out = findViewById(R.id.tv_map_out);

        tv_name.setText(showTitleName());

        if (showMoreIcon() == 0) {
            iv_more.setVisibility(View.GONE);
        } else {
            iv_more.setVisibility(View.VISIBLE);
            iv_more_icon.setBackgroundResource(showMoreIcon());
        }

        if (showNavigation()) {
            bar_lin.setVisibility(View.VISIBLE);
        } else {
            bar_lin.setVisibility(View.GONE);
        }
        if (showMedia()) {

            try {
                media = findViewById(R.id.media);
                add_video1 = findViewById(R.id.add_video1);
                iv_video_close = findViewById(R.id.iv_video_close);
                iv_video_close.setVisibility(View.GONE);
                mRecyclerView = findViewById(R.id.recyclerView);
                imageFileAdapter = new ImageFileAdapter(mContext);
                mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL) {
                    @Override
                    public boolean canScrollVertically() {
                        return false;
                    }
                });
                mRecyclerView.setAdapter(imageFileAdapter);

                filelist.add(new FileIndexBean(true));
                imageFileAdapter.setNewData(filelist);

            } catch (Exception e) {
                ToastShow("缺少布局文件！Code:item_media");
            }
        }

    }

    private void initEvent() {

        tv_map_in.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMapView.zoomin();
            }
        });
        tv_map_out.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMapView.zoomout();
            }
        });


        tv_map_mylocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (CacheData.Cache_MyLocation != null) {

                    Point[] ps = new Point[]{new Point(111317.25989248542,52107.52365473713),
                            new Point(111317.25989248542,35306.44838591994),
                            new Point(93037.91742573508,35306.44838591994),
                            new Point(93037.91742573508,52107.52365473713)};
//            x表示当地的纬度,y表示当地的经度。
                    //X最大111317.25989248542   X最小93037.91742573508   Y最大52107.52365473713  Y最小35306.44838591994

                    if (!isPtInPoly(CacheData.Cache_MyLocation.getX(), CacheData.Cache_MyLocation.getY(),ps)){

                        ToastShow("当前所在位置不在地图范围内");

                        return;
                    }


                    mMapView.zoomToResolution(new Point(CacheData.Cache_MyLocation.getX(), CacheData.Cache_MyLocation.getY()), 11);
                    //   mMapView.centerAt(new Point(CacheData.Cache_MyLocation.getX(),CacheData.Cache_MyLocation.getY()),true);
                } else {
                    ToastShow("当前GPS未获取到位置，请稍后重试！");
                }
            }
        });


        if (showMedia()) {
            add_video1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (vediofilelist.size() > 0) {
                      //  ToastShow("预览视频");
                    } else {
                        getVideoFromCamera();
                    }
                }
            });

            iv_video_close.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    vediofilelist.clear();
                    add_video1.setImageResource(R.mipmap.icon_addpic_unfocused);
                    iv_video_close.setVisibility(View.GONE);
                }
            });

            imageFileAdapter.setOnItemChildClickListener(new BaseAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseAdapter adapter, View v, int position) {
                    FileIndexBean fileItem = imageFileAdapter.getItem(position);


                    if (v.getId() == R.id.iv_close) {
                        //删除fileList
                        filelist.remove(fileItem);
                        imageFileAdapter.setNewData(filelist);
                        return;
                    }

                    if (v.getId() == R.id.iv) {

                        if (position == filelist.size() - 1) {

                            if (filelist.size() <= 8) {
                                Camera();
                            } else {
                                ToastShow("目前图片最大支持8张！");
                            }
                        } else {
                            ToastShow("预览");
                        }

                    }

                }
            });

        }

    }

    //添加点
    protected void addpoint(Point mapPoint) {
        gLayerPos.removeAll();
        PictureMarkerSymbol locationSymbol = new PictureMarkerSymbol(mContext.getResources().getDrawable(R.mipmap.icon_geo_blue));
        Graphic graphic = new Graphic(mapPoint, locationSymbol);
        gLayerPos.addGraphic(graphic);
    }

    //添加点
    protected void addpoint(Point mapPoint, int icon) {
        gLayerPos.removeAll();
        PictureMarkerSymbol locationSymbol = new PictureMarkerSymbol(mContext.getResources().getDrawable(icon));
        Graphic graphic = new Graphic(mapPoint, locationSymbol);
        gLayerPos.addGraphic(graphic);
    }


    protected void initMyLocation() {
        gMyLocationLayer.removeAll();
        if (CacheData.Cache_MyLocation != null) {

            Point[] ps = new Point[]{new Point(111317.25989248542,52107.52365473713),
                    new Point(111317.25989248542,35306.44838591994),
                    new Point(93037.91742573508,35306.44838591994),
                    new Point(93037.91742573508,52107.52365473713)};
//            x表示当地的纬度,y表示当地的经度。
            //X最大111317.25989248542   X最小93037.91742573508   Y最大52107.52365473713  Y最小35306.44838591994

            if (!isPtInPoly(CacheData.Cache_MyLocation.getX(), CacheData.Cache_MyLocation.getY(),ps)){

                ToastShow("当前所在位置不在地图范围内");

                return;
            }

            Point mapPoint = new Point(CacheData.Cache_MyLocation.getX(), CacheData.Cache_MyLocation.getY());
            PictureMarkerSymbol locationSymbol = new PictureMarkerSymbol(mContext.getResources().getDrawable(R.mipmap.icon_geo_blue));
            Graphic graphic = new Graphic(mapPoint, locationSymbol);
            gMyLocationLayer.addGraphic(graphic);
            mMapView.centerAt(mapPoint, true);
        }
    }

    public static boolean isPtInPoly (double ALon , double ALat , Point[] ps) {
        int iSum, iCount, iIndex;
        double dLon1 = 0, dLon2 = 0, dLat1 = 0, dLat2 = 0, dLon;
        if (ps.length < 3) {
            return false;
        }
        iSum = 0;
        iCount = ps.length;
        for (iIndex = 0; iIndex<iCount;iIndex++) {
            if (iIndex == iCount - 1) {
                dLon1 = ps[iIndex].getX();
                dLat1 = ps[iIndex].getY();
                dLon2 = ps[0].getX();
                dLat2 = ps[0].getY();
            } else {
                dLon1 = ps[iIndex].getX();
                dLat1 = ps[iIndex].getY();
                dLon2 = ps[iIndex + 1].getX();
                dLat2 = ps[iIndex + 1].getY();
            }
            // 以下语句判断A点是否在边的两端点的水平平行线之间，在则可能有交点，开始判断交点是否在左射线上
            if (((ALat >= dLat1) && (ALat < dLat2)) || ((ALat >= dLat2) && (ALat < dLat1))) {
                if (Math.abs(dLat1 - dLat2) > 0) {
                    //得到 A点向左射线与边的交点的x坐标：
                    dLon = dLon1 - ((dLon1 - dLon2) * (dLat1 - ALat) ) / (dLat1 - dLat2);
                    // 如果交点在A点左侧（说明是做射线与 边的交点），则射线与边的全部交点数加一：
                    if (dLon < ALon) {
                        iSum++;
                    }
                }
            }
        }
        if ((iSum % 2) != 0) {
            return true;
        }
        return false;
    }

    protected int GetIcon(String str, String type) {

        try {
            if (str == null) {
                return 0;
            }

            switch (str) {
                case "WSC"://污水厂
                    if (type.equals("0")) {
                        return R.mipmap.map_wsc_g;
                    } else if (type.equals("3")) {
                        return R.mipmap.map_wsc_gray;
                    } else {
                        return R.mipmap.map_wsc_r;
                    }
                case "BZ"://泵站
                    if (type.equals("0")) {
                        return R.mipmap.map_bz_g;
                    } else if (type.equals("3")) {
                        return R.mipmap.map_bz_gray;
                    } else {
                        return R.mipmap.map_bz_r;
                    }
                case "GWJC_GWYW"://管网液位
                    if (type.equals("0")) {
                        return R.mipmap.map_gwyw_g;
                    } else if (type.equals("3")) {
                        return R.mipmap.map_gwyw_gray;
                    } else {
                        return R.mipmap.map_gwyw_r;
                    }
                case "GWJC_GWLL"://管网流量
                    if (type.equals("0")) {
                        return R.mipmap.map_gwll_g;
                    } else if (type.equals("3")) {
                        return R.mipmap.map_gwll_gray;
                    } else {
                        return R.mipmap.map_gwll_r;
                    }
                case "GWJC_GWSZ"://管网水质
                    if (type.equals("0")) {
                        return R.mipmap.map_gwsz_g;
                    } else if (type.equals("3")) {
                        return R.mipmap.map_gwsz_gray;
                    } else {
                        return R.mipmap.map_gwsz_r;
                    }
                case "JSC"://积水尺
                    if (type.equals("0")) {
                        return R.mipmap.map_jsc_g;
                    } else if (type.equals("3")) {
                        return R.mipmap.map_jsc_gray;
                    } else {
                        return R.mipmap.map_jsc_r;
                    }
                case "ZGYL"://积水尺
                    if (type.equals("0")) {
                        return R.mipmap.map_zgyl_g;
                    } else if (type.equals("3")) {
                        return R.mipmap.map_zgyl_gray;
                    } else {
                        return R.mipmap.map_zgyl_r;
                    }
                default:
                    return 0;
            }

        } catch (Exception e) {
            return 0;
        }

    }


    @SuppressLint("NewApi")
    private void initWindows() {
        Window window = getWindow();
        int color = getResources().getColor(android.R.color.transparent);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //| WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    // | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            //设置状态栏颜色
            window.setStatusBarColor(color);
            //设置导航栏颜色
            // window.setNavigationBarColor(color);
            ViewGroup contentView = ((ViewGroup) findViewById(android.R.id.content));
            View childAt = contentView.getChildAt(0);
            if (childAt != null) {
                childAt.setFitsSystemWindows(true);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            // window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            //设置contentview为fitsSystemWindows
            ViewGroup contentView = (ViewGroup) findViewById(android.R.id.content);
            View childAt = contentView.getChildAt(0);
            if (childAt != null) {
                childAt.setFitsSystemWindows(true);
            }
            //给statusbar着色
            View view = new View(mContext);
            view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight()));
            view.setBackgroundColor(color);
            contentView.addView(view);
        }
    }

    /**
     * 获取导航栏高度
     *
     * @return 导航栏高度
     */
    public static int getNavigationBarHeight() {
        int resourceId = mContext.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
        return mContext.getResources().getDimensionPixelSize(resourceId);
    }

    /**
     * 获取状态栏高度
     *
     * @return 状态栏高度
     */
    private static int getStatusBarHeight() {
        // 获得状态栏高度
        int resourceId = mContext.getResources().getIdentifier("status_bar_height", "dimen", "android");
        return mContext.getResources().getDimensionPixelSize(resourceId);
    }


    protected void Camera() {
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("获取图片途径");
        builder.setPositiveButton("拍照", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                getImageFromCamera();
            }
        });

        builder.setNegativeButton("相册",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        getImageFromAlbum();
                    }
                });

        builder.create().show();

    }

    protected void getImageFromAlbum() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
        } else {
            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);

    }


    protected void getVideoFromCamera() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
            String out_file_path = Environment.getExternalStorageDirectory().getPath() + "/" + Config.APP_Code + "/video/";
            File dir = new File(out_file_path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            capturePath = out_file_path + GetCommonParameters.getNowTimetoString() + ".wmv";
            intent.putExtra(MediaStore.EXTRA_OUTPUT, GetCommonParameters.GetFileProviderUri(mContext, capturePath));
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
            intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);//限制录制时间10秒
            startActivityForResult(intent, REQUEST_CODE_CAPTURE_VIDEO);
            //ToastShow("视频只能录制10秒！");
        } else {
            Toast.makeText(getApplicationContext(), "请确认已经插入SD卡", Toast.LENGTH_LONG).show();
        }
    }


    protected void getImageFromCamera() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
            String out_file_path = Environment.getExternalStorageDirectory().getPath() + "/" + Config.APP_Code + "/camera/";
            File dir = new File(out_file_path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            capturePath = out_file_path + GetCommonParameters.getNowTimetoString() + ".jpg";
            intent.putExtra(MediaStore.EXTRA_OUTPUT, GetCommonParameters.GetFileProviderUri(mContext, capturePath));
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
            startActivityForResult(intent, REQUEST_CODE_CAPTURE_CAMEIA);
        } else {
            Toast.makeText(getApplicationContext(), "请确认已经插入SD卡", Toast.LENGTH_LONG).show();
        }
    }


    protected void showImage(String ImgUrl) {

        //删除为空的文件
        for (FileIndexBean m : filelist) {
            if (m.isAdd()) {
                filelist.remove(m);
            }
        }

        filelist.add(new FileIndexBean(filelist.size() + 1, ImgUrl));
        filelist.add(new FileIndexBean(true));
        imageFileAdapter.setNewData(filelist);

    }


    protected void showVideoImage(String videoUrl) {
        File file = new File(videoUrl);
        vediofilelist.add(file);
        iv_video_close.setVisibility(View.VISIBLE);
        add_video1.setImageResource(R.mipmap.icon_record);
    }


    protected List<File> GetFilelist() {
        List<File> files = new ArrayList<>();

        for (FileIndexBean f : filelist) {
            if (!f.isAdd()) {
                File imgfile = new File(f.getFileUrl());

                //ToastShow("SIZE:"+imgfile.length());
                Bitmap mp = ImageUtils.getBitmapFromFilePath(f.getFileUrl());
                File newFile = GetCommonParameters.saveFile(mp, imgfile.getName());

                files.add(newFile);
            }
        }

        if (vediofilelist.size() > 0) {
            files.add(vediofilelist.get(0));
        }

        return files;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_PICK_IMAGE && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                Uri uri = data.getData();
                String url = GetCommonParameters.getRealFilePath(mContext, uri);
                showImage(url);
            }

        } else if (requestCode == REQUEST_CODE_CAPTURE_CAMEIA && resultCode == Activity.RESULT_OK) {
            showImage(capturePath);

        } else if (requestCode == REQUEST_CODE_CAPTURE_VIDEO && resultCode == Activity.RESULT_OK) {
            //压缩文件
            String out_file_path = Environment.getExternalStorageDirectory().getPath() + "/" + Config.APP_Code + "/video/thumb/";
            File dir = new File(out_file_path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            //获取文件名称
            String name = capturePath;
            int index = name.indexOf("video");
            String filename = name.substring(index + 6, name.length());
            String videourl = out_file_path + filename;
            compressVideoResouce(mContext, capturePath, videourl);
            ToastShow("视频处理中");
        }

    }


    /**
     * 压缩视频
     *
     * @param mContext
     * @param filepath
     */
    public void compressVideoResouce(Context mContext, String filepath, final String newfilepath) {
        if (MyTextUtils.IsNullByString(filepath)) {
            ToastShow("请先选择转码文件！");
            return;
        }
        //PLShortVideoTranscoder初始化，三个参数，第一个context，第二个要压缩文件的路径，第三个视频压缩后输出的路径
        PLShortVideoTranscoder mShortVideoTranscoder = new PLShortVideoTranscoder(mContext, filepath, newfilepath);
        MediaMetadataRetriever retr = new MediaMetadataRetriever();
        retr.setDataSource(filepath);
        String height = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT); // 视频高度
        String width = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH); // 视频宽度
        String rotation = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION); // 视频旋转方向
        int transcodingBitrateLevel = 6;//我这里选择的2500*1000压缩，这里可以自己选择合适的压缩比例
        mShortVideoTranscoder.transcode(Integer.parseInt(width), Integer.parseInt(height), getEncodingBitrateLevel(transcodingBitrateLevel), false, new PLVideoSaveListener() {
            @Override
            public void onSaveVideoSuccess(String s) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showVideoImage(newfilepath);
                        ToastShow("压缩完成！");
                    }
                });
            }

            @Override
            public void onSaveVideoFailed(final int errorCode) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        switch (errorCode) {
                            case ERROR_NO_VIDEO_TRACK:
                                ToastShow("该文件没有视频信息！");
                                break;
                            case ERROR_SRC_DST_SAME_FILE_PATH:
                                ToastShow("源文件路径和目标路径不能相同！");
                                break;
                            case ERROR_LOW_MEMORY:
                                ToastShow("手机内存不足，无法对该视频进行时光倒流！");
                                break;
                            default:
                                ToastShow("transcode failed: " + errorCode);
                        }
                    }
                });
            }

            @Override
            public void onSaveVideoCanceled() {
//                LogUtil.e("onSaveVideoCanceled");
            }

            @Override
            public void onProgressUpdate(float percentage) {
//				runOnUiThread(new Runnable() {
//					@Override
//					public void run() {
//						showVideoImage(newfilepath);
//						ToastShow("压缩完成！");
//					}
//				});
                Log.d("info", "onProgressUpdate==========" + percentage);
            }
        });
    }

    /**
     * 设置压缩质量
     *
     * @param position
     * @return
     */
    private int getEncodingBitrateLevel(int position) {
        return ENCODING_BITRATE_LEVEL_ARRAY[position];
    }

    /**
     * 选的越高文件质量越大，质量越好
     */
    public static final int[] ENCODING_BITRATE_LEVEL_ARRAY = {
            500 * 1000,
            800 * 1000,
            1000 * 1000,
            1200 * 1000,
            1600 * 1000,
            2000 * 1000,
            2500 * 1000,
            4000 * 1000,
            8000 * 1000,
    };


    protected void ToastShow(String msg) {
        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
    }

}
